package kr.couponplay.android.support;

import java.io.ByteArrayInputStream;
import java.security.MessageDigest;

public class StringUtils {
	public static String substringForLast(String str, int length) {
		if (str != null && str.length() > 0) {
			str = str.substring(0, str.length() + (length));
		}
		return str;
	}

	public static boolean isEmpty(String str) {
		if (str == null) {
			return true;
		}
		if (str.trim().length() == 0) {
			return true;
		}
		return false;
	}

	public static boolean isNotEmpty(String str) {
		if (isEmpty(str)) {
			return false;
		}
		return true;
	}

	public static String trimToEmpty(String str) {
		if (str == null) {
			return "";
		}
		return str.trim();
	}

	public static String getSha1Hash(String input) throws Exception {
		String retval = null;
		ByteArrayInputStream inputStream = new ByteArrayInputStream(input.getBytes("UTF-8"));
		MessageDigest hash = MessageDigest.getInstance("SHA1");
		byte[] buffer = new byte[1024];

		int numRead = 0;
		while ((numRead = inputStream.read(buffer)) != -1) {
			hash.update(buffer, 0, numRead);
		}

		retval = toHexString(hash.digest());
		return retval;

	}

	protected static final byte[] Hexhars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	public static String toHexString(byte[] input) {
		StringBuilder buf = new StringBuilder(2 * input.length);
		for (int i = 0; i < input.length; i++) {
			int v = input[i] & 0xff;
			buf.append((char) Hexhars[v >> 4]);
			buf.append((char) Hexhars[v & 0xf]);
		}
		return buf.toString();
	}
}
